﻿@implements IDisposable
@inherits AdminCompontentBase;
@inject GlobalConfig GlobalConfig;

<MDialog @bind-Value="Show" Width=300>
    <MCard>
        <MCardTitle Class="text-h5">
            @Title
        </MCardTitle>

         <MCardText>
            @Message
        </MCardText>

        <MCardActions>
            <MSpacer></MSpacer>
            <MButton OnClick="async ()=> await Confirm(false)">
                @T("Cancel")
            </MButton>
            <MButton Color="primary"
                     OnClick="async ()=> await Confirm(true)">
                @T("Confirm")
            </MButton>
        </MCardActions>
    </MCard>
</MDialog>

@code {
    [Parameter]
    public bool Show { get; set; }

    [Parameter]
    public EventCallback<bool> ShowChanged { get; set; }

    [Parameter]
    public string? Title { get; set; }

    [Parameter]
    public string? Message { get; set; }

    [Parameter]
    public EventCallback<bool> WhenConfirm { get; set; }

    async Task Confirm(bool confirm)
    {
        if (ShowChanged.HasDelegate)
        {
            await ShowChanged.InvokeAsync(false);
        }
        else Show = false;

        base.StateHasChanged();

        if (WhenConfirm.HasDelegate)
        {
            await WhenConfirm.InvokeAsync(confirm);
        }     
    }

    void Confirm(string title, string message, EventCallback<bool> whenConfirm)
    {
        Title = title;
        Message = message;
        WhenConfirm = whenConfirm;
        Show = true;

        base.StateHasChanged();
    }

    protected override void OnInitialized()
    {
        GlobalConfig.OnConfirmChanged += Confirm;
    }

    public void Dispose()
    {
        GlobalConfig.OnConfirmChanged -= Confirm;
    }
}
